package com.mocoop.plugin.user;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.json.JSONException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;

import com.mocoop.activity.MocoopActivity;
import com.mocoop.entity.AppBase;
import com.mocoop.jfqc.LoginActivity;
import com.mocoop.jfqc.MainActivity;
import com.mocoop.jfqc.MainActivity.UpdateInterface;
import com.mocoop.jfqc.R;
import com.mocoop.plugin.MocoopPlugin;

public class UserManager extends MocoopPlugin {
	@Override
	public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
		if ("getUserInfo".equals(action)) {
			getUserInfo(callbackContext);
		} else if ("logoutUser".equals(action)) {
			logoutUser();
		}else if(action.equals("checkUpdate")){
			((MainActivity)getActivity()).checkUpdate(new UpdateInterface() {
				
				@Override
				public void updateCallBack(AppBase appInfo, int icon,String headName) {
					if(appInfo == null){
						Toast.makeText(getActivity(), R.string.newest_version, Toast.LENGTH_LONG).show();
					}else{
						((MainActivity)getActivity()).doNewVersionUpdate(appInfo, icon,headName);
					}
				}
			});
			
			callbackContext.success();
		}
		return true;
	}

	private void logoutUser() {
		getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
		getActivity().overridePendingTransition(R.anim.my_slide_in_from_left, R.anim.my_slide_still);
		getActivity().finish();
	}

	private void getUserInfo(CallbackContext callbackContext) {
		SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MocoopActivity.MOCOOP_CONFIG, 0);
		
		String userInfo = sharedPreferences.getString(MocoopActivity.USER_INFO, "");
		if ("".equals(userInfo)) {
			callbackContext.error("找到不用户信息");
		} else {
			callbackContext.success(userInfo);
		}
	}
}
